﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Birkelund.QueryStrings.Internals
{
    /// <summary>
    /// An algorithm which does some obfucation to generate a relatively short checksum key. 
    /// The algoritm is not very secure as it is easily broken by brute force
    /// </summary>
    internal class BasicChecksumCalculator : IChecksumCalculator
    {
        public string CalculateCheckSum(IEnumerable<TokenKeyValue> allTokens)
        {
            ArgumentValidation.ThrowIfNull(allTokens, "allTokens");

            TokenKeyValue[] tokens = allTokens.ToArray();

            int checkSum = 0;
            for (int i = 0; i < tokens.Length; i++)
            {
                int valueToAdd = CalculateSingleCheckSum(tokens[i]) * (i + 1);
                checkSum += valueToAdd;
            }
            checkSum *= 1414; //put in a randomly chosen value to obfuscate a bit
            return checkSum.ToString("X"); //Hexadecimal
        }

        private int CalculateSingleCheckSum(TokenKeyValue token)
        {
            int charSum = 0;
            for (int i = 0; i < token.Value.Length; i++)
            {
                charSum += (int)token.Value[i] * (i + 1);
            }
                
            int valueToAdd = (token.Key.Length + token.Value.Length + charSum);
            return Convert.ToInt32(valueToAdd);
        }
    }
}